package net.gcode.sdkscheduleparser.core.read;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import net.gcode.sdkscheduleparser.gui.Objects;

public class Reader {
	private static String lastString = "";
	/*
	 * false= <param=test> true=<param="test">
	 */
	private static Boolean type = false;

	public Reader() {

	}

	public static String read(String planpfad) {
		Objects.setStatus("Lesen den Stundenplan ein.");
		lastString = "";
		try {

			if (planpfad.indexOf("http:") != -1) {
				readURL(planpfad);
			} else {
				readFile(planpfad);
			}
		} catch (Exception e) {
			System.out.println("Datei kann nicht gelesen werden" + e.getMessage());
		}
		return lastString;
	}

	public static String readURL(String filename) throws IOException {
		URL url = new URL(filename);
		String lineSep = System.getProperty("line.separator");
		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

		String inputLine;

		StringBuffer sb = new StringBuffer();
		while ((inputLine = in.readLine()) != null) {
			sb.append(inputLine);
			sb.append(lineSep);
		}
		in.close();
		lastString = sb.toString();
		type = false;
		return lastString;

	}

	public static String readFile(String filename) throws IOException {
		String lineSep = System.getProperty("line.separator");
		BufferedReader br = new BufferedReader(new FileReader(filename));
		String nextLine = "";
		StringBuffer sb = new StringBuffer();
		while ((nextLine = br.readLine()) != null) {
			sb.append(nextLine);

			sb.append(lineSep);
		}
		lastString = sb.toString();
		type = true;
		return lastString;
	}

	public static String getLastString() {
		return lastString;
	}

	public static Boolean getType() {
		return type;
	}
}
